package com.capgemini.expense.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.capgemini.expense.model.ExpenseContext;

public class TokenDao extends JPADao<ExpenseContext> {

	public TokenDao() {
		this.managedEntitiesType = ExpenseContext.class;
	}

	@SuppressWarnings("unchecked")
	public ExpenseContext getByToken(String token) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("SELECT e FROM ExpenseContext e WHERE e.token = :token");
			q.setParameter("token", token);
			List<ExpenseContext> result = q.getResultList();
			if (result == null || result.size() == 0) {
				return null;
			} else {
				return (ExpenseContext) result.get(0);
			}
		} finally {
			em.close();
		}
	}

	public void clearInvalidTokens(Date date) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("DELETE FROM ExpenseContext e WHERE e.lastAccess < :lastAccess");
			q.setParameter("lastAccess", date);
			q.executeUpdate();
		} finally {
			em.close();
		}
	}
}
